<template>
  <div class="tas-main">
    <!-- 风险源 -->
    <div class="source-class">
      <label>工单分类：</label>
      <el-radio-group v-model="source" @input="initPage">
        <el-radio-button :label="item.source" v-for="item in orderClass" :key="item.source"
          >{{ item.desc }}（{{ item.count }}）</el-radio-button
        >
      </el-radio-group>
    </div>
    <sec-ext-table
      :reserveSelection="true"
      :rowKey="getRowId"
      :selection="true"
      :default-sort="sortProp"
      ref="secTableRef"
      @selection-change="handleSelectionChange"
      :tableData="tableData"
      :tableCol="tableCol"
      :loadingProp="loadingProp"
      :filterCol="filterCol"
      @filter-confirm="filterConfirm"
      @search-change="searchChange"
      @sort-change="sortChange"
    >
      <el-button
        type="primary"
        v-if="['pending'].includes(status)"
        :disabled="isBatchDisable"
        @click="receiveOrRejectHandle(null, true)"
        >批量认领</el-button
      >
      <el-button
        type="primary"
        v-if="['doing'].includes(status)"
        :disabled="isBatchDisable"
        @click="delayDateHandle(null)"
        >批量延期</el-button
      >
      <el-button
        type="primary"
        v-if="['pending'].includes(status)"
        :disabled="isBatchDisable"
        @click="receiveOrRejectHandle(null, false)"
        >批量驳回</el-button
      >
      <!-- <el-button type="primary" v-if="['doing'].includes(status)" :disabled="isBatchDisable" @click="handle(null)"
        >批量处理</el-button
      > -->
      <el-button
        type="primary"
        v-if="['pending', 'doing'].includes(status) && !['all'].includes(source)"
        :disabled="isBatchDisable"
        @click="handleDeliver(null)"
        >批量转交</el-button
      >
      <el-button
        type="primary"
        v-if="['pending', 'doing'].includes(status) && !['all'].includes(source) && !['audit-api'].includes(type)"
        :disabled="isBatchDisable"
        @click="handleCloseOrder(null)"
        >批量申诉</el-button
      >
      <span v-if="sourceItem.note" class="info" slot="center">
        <!-- <strong>{{ sourceItem.sourceLabel }}：</strong> -->
        <el-tag style="font-weight: 600" size="medium" type="danger">{{ sourceItem.note }}</el-tag>
        <!-- <strong style="color: red">{{ sourceItem.note }}</strong> -->
      </span>
      <template v-slot:leader="{ data }">
        <dc-user :name="data.row.leader"></dc-user>
      </template>
    </sec-ext-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="page"
      background
      :layout="layout"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      :total="totalSize"
    >
    </el-pagination>
    <!-- 转交 -->
    <el-dialog title="转交" append-to-body width="80%" @close="diaClose" :visible.sync="isShowDeliver">
      <account-change
        ref="accountChangeRef"
        v-if="isShowDeliver"
        :datas="selRows"
        :operateType="3"
        :isBatch="isBatch"
        @cancel="isShowDeliver = false"
        @confirm-success="deliverConfirmSuccess"
      ></account-change>
    </el-dialog>
    <!-- 申诉 -->
    <el-dialog
      title="申诉（发起BPM审批）"
      @close="diaClose"
      append-to-body
      width="60%"
      :visible.sync="isShowCloseOrder"
    >
      <close-order
        :datas="selRows"
        v-if="isShowCloseOrder"
        @cancel="isShowCloseOrder = false"
        @confirm-success="closeOrderSuccess"
      ></close-order>
    </el-dialog>
    <!-- 延期 -->
    <el-dialog title="延期" @close="diaClose" :append-to-body="true" width="60%" :visible.sync="delayDiaShow">
      <delay-date-Form
        :datas="selRows"
        v-if="delayDiaShow"
        @cancel="delayDiaShow = false"
        @confirm-success="delaySuccess"
      ></delay-date-Form>
    </el-dialog>
    <!-- 处理 -->
    <el-dialog :title="title" append-to-body width="60%" :visible.sync="apiDiaShow"
      ><iframe
        style="width: 100%; height: 500px"
        id="h5-page"
        v-if="apiDiaShow"
        ref="iframeH5"
        :src="srcH5"
        frameborder="0"
        @load="loaded"
      ></iframe>
    </el-dialog>
    <!-- 操作提示弹框  暂时没用到 改成划过每个按钮tooltip-->
    <el-dialog title="操作提示" :append-to-body="true" width="520px" :visible.sync="isShowOperationTip">
      <operator-tip :source="source"></operator-tip>
    </el-dialog>
    <!-- 单个认领弹框 -->
    <el-dialog title="认领" :append-to-body="true" width="520px" :visible.sync="receiveIsShow">
      <div class="receive-content">
        <i class="el-icon-warning"></i>
        <div>工单认领，是否继续？（认领后仍可转交或申诉）</div>
      </div>
      <div class="receive-opt-box">
        <el-button @click="receiveIsShow = false">取消</el-button>
        <el-button @click="receiveConfirmHandle()">确定</el-button>
        <el-button @click="receiveConfirmHandle(true)" type="primary">确定并打开详情</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { paginationMixin } from "@/mixins/pagination";
import { orderOptMixin } from "@/mixins/orderOpt";

import { getFeModelCfgList } from "api/riskCenterApi";
import { getSourceAndCountListApi, getOrderListBySearchAndFilterApi, receiveOrRejectApi } from "api/taskCenterApi";
import { helpConfigApi } from "api/api";

import operatorTip from "./component/operatorTip.vue";
import closeOrder from "./component/closeOrder";
import accountChange from "components/accountChange";
import delayDateForm from "./component/delayDate";

import operationBtnData from "./model";
export default {
  name: "taskCenter",
  props: {},
  mixins: [paginationMixin, orderOptMixin],
  components: { operatorTip, closeOrder, accountChange, delayDateForm },
  data() {
    return {
      receiveIsShow: false, //单个认领是否展示
      isBatch: false, //点击批量的操作/表格操作列
      orderClass: [], //工单分类
      type: "",
      source: "",
      selRows: [],
      sortProp: { prop: "createTime", order: "descending" }, //排序的数据
      tableData: [],
      tableCol: [],
      filterCol: [],

      isShowOperationTip: false, //表格操作列 点击问号 弹框内容
      config: [], //帮助中心 source的简介数据
      //放在orderOptMixin了
      // isShowCloseOrder: false, //申诉
      // isShowDeliver: false, //转交 是否展示
      // delayDiaShow: false, //延期 是否展示
      // //处理使用
      // title: "",
      // srcH5: "",
      // apiDiaShow: false,
    };
  },
  computed: {
    status() {
      return this.$route.params.status;
    },
    sourceItem() {
      let sourceItem = this.config.find((item) => item.source === this.source);
      console.log("sourceItem", sourceItem);
      return sourceItem ? { sourceLabel: sourceItem.sourceLabel || "", note: sourceItem.note } : {};
    },
    isBatchDisable() {
      if (this.selRows.length == 0) return true;
      //appeal:1/3 申诉中/验收中
      return this.selRows.some((item) => item.appeal === "1" || item.appeal === "3");
    },
  },
  watch: {},
  mounted() {},
  async created() {
    this.operation = {
      type: "operation",
      label: "操作",
      width: 200,
      // renderHeader: this.renderHeader,
      children: [
        ...operationBtnData.bind(this)(),
        {
          label: "详情",
          click: ({ row }) => {
            this.btnOmegaTrack("detail", "详情");
            this.handleCheckDetail(row, true);
          },
        },
      ],
    };
    this.initOmegaTrack(); //界面级
    this.initHelpConfig();
    await this.getOrderClass(); //工单分类

    this.initPage();
  },
  methods: {
    //单个认领
    receiveHandle(row) {
      this.receiveIsShow = true;
      this.selRows = [row];
    },
    receiveConfirmHandle(openDetail) {
      //认领 埋点
      this.btnOmegaTrack("claim", "认领");
      let rows = this.selRows.map((item) => ({ ...item, isReceive: true }));
      receiveOrRejectApi(rows).then((res) => {
        console.log("[ res ] >", res);
        if (res.code == 0) {
          this.receiveIsShow = false;
          if (openDetail) {
            let row = this.selRows[0];
            this.utils.$router(
              {
                path: `/task/doing/${row.source}`,
                query: {
                  type: row.type,
                  processId: row.processId,
                  uniqueId: row.uniqueId,
                  caseId: row.caseId,
                  isDetail: true,
                  from: "page",
                },
              },
              "_blank",
            );
          } else {
            let message = "认领成功，请至”进行中“菜单进行治理";
            this.message.success({ message });
            //工单列表才会执行
            this.getOrderClass?.(); //工单分类
            this.initPage();
          }
        }
      });
    },
    initHelpConfig() {
      helpConfigApi().then((res) => {
        let data = res.data[0];
        this.config = JSON.parse(data.params.config);
        console.log("[ this.config ] >", this.config);
      });
    },
    initOmegaTrack() {
      let statusLabel = { todo: "待认领", doing: "进行中", done: "已完成" };
      let status = this.status == "pending" ? "todo" : this.status;
      let eventId = `${status}_sw`;
      let eventLabel = `工单中心-${statusLabel[status]}`;
      this.utils.omegaTrackEvent(eventId, eventLabel);
    },
    btnOmegaTrack(id, label) {
      let statusLabel = { pending: "待认领", doing: "进行中", done: "已完成" };
      let status = this.status == "pending" ? "todo" : this.status;
      let eventId = `${status}_${id}_ck`;
      let eventLabel = `工单中心-${statusLabel[eventId]}-${label}`;
      this.utils.omegaTrackEvent(eventId, eventLabel, { page: "list" });
    },
    setType() {
      //选择是全部的时候，type:order
      console.log("source", this.source);
      console.log("orderClass", this.orderClass);
      this.type = this.orderClass.find((item) => item.source === this.source)?.type || "order";
    },
    initPage() {
      this.setType();
      this.setStateInfo();
      //初始化表格头，防止表格列顺序错乱
      this.tableCol = [];
      this.$nextTick(() => {
        //初始化筛选内容和搜索框数据
        //todo 如果搜素框输入完之后 直接去切换source 的tab会出现切换不了的情况。因为输入框失焦在了el-radio上
        this.searchVal = "";
        this.filter = [];
        this.$refs.secTableRef.reset(); //初始化选择框和筛选项以及字段设置

        this.initTableCol();
        this.initTableData();
      });
    },
    setStateInfo() {
      let source = this.source === "all" ? "" : this.source;
      this.$store.commit("setType", "order"); //筛选使用到的接口 type：order
      this.$store.commit("setSource", source);
    },
    getParams() {
      let { status } = this.$route.params;
      return {
        type: this.type,
        source: this.source == "all" ? "" : this.source,
        status,
      };
    },
    async getOrderClass() {
      let { status } = this.$route.params;
      console.log("[ status ] >", status);
      await getSourceAndCountListApi({ orderStatus: status }).then((res) => {
        console.log("[ res ] >", res);
        let data = res.data;
        //获取总数
        let allCount = data.reduce((prev, cur) => prev + cur.count, 0);
        let all = { count: allCount, desc: "全部", source: "all", type: "order" };
        //筛选掉count为0的源  如果都为零（留下一个为了界面美观）
        let filterData = data.filter((item) => item.count > 0);
        filterData.length === 0 && filterData.push(data[0]);

        this.orderClass = [all, ...filterData];
        this.source = this.source ? this.source : this.orderClass[1].source;
      });
    },
    getRowId(row) {
      return row.processId;
    },
    handleSelectionChange(val) {
      console.log("selRows", val);
      this.selRows = val;
    },
    searchChange(val) {
      console.log("[ val ] >", val);
      this.searchVal = val;
      this.page = 1;
      this.initTableData();
    },
    filterConfirm(data) {
      this.filter = data;
      this.page = 1;
      this.initTableData();
    },
    initTableCol() {
      getFeModelCfgList({ ...this.getParams(), type: "order" }).then((res) => {
        let data = res.data;
        console.log("[ data ] >", data);
        let { tableCol, filterCol } = new this.ConfigCondition({
          data: data,
          // exclude: ["uniqueId"],
          // type: { slot: ["leader"] },
        });
        this.tableCol = tableCol;
        this.tableCol.push(this.operation);

        this.filterCol = filterCol;
      });
    },
    initTableData() {
      let loading = this.openLoading();
      let { prop, order } = this.sortProp;
      getOrderListBySearchAndFilterApi({
        type: this.type,
        source: this.source == "all" ? "" : this.source,
        status: this.$route.params.status,
        pageNum: this.page,
        pageSize: this.pageSize,
        searchCnt: this.searchVal,
        filter: this.filter,
        orderField: prop, //排序字段
        sort: this.formatSort(order), //排序方式
      }).then((res) => {
        loading.close();
        this.tableData = res.data || [];
        console.log("[ res ] >", res);
        this.totalSize = res.count;
      });
    },
    formatSort(orderParams) {
      if (!orderParams) return "";
      let order = "";
      if (orderParams == "ascending") {
        order = "asc";
      } else if (orderParams == "descending") {
        order = "desc";
      }
      return order;
    },
    sortChange({ column }) {
      //如果取消排序，把字段值也赋值成空
      let prop = column.order ? column.property : "";
      this.sortProp = { prop, order: column.order };
      this.initTableData();
    },

    renderHeader(h, { column }) {
      // h即为creatElement的简写，具体可看vue官方文档
      return h("div", [
        h("span", column.label),
        h("i", {
          class: "el-icon-question",
          style: "margin-left:5px; cursor: pointer;",
          on: {
            click: () => {
              this.isShowOperationTip = true;
            },
          },
        }),
      ]);
    },
    handleCheckDetail(row, isDetail) {
      let { status } = this.getParams();
      this.utils.$router(
        {
          path: `/task/${status}/${row.source}`,
          query: {
            type: row.type,
            processId: row.processId,
            uniqueId: row.uniqueId,
            caseId: row.caseId,
            isDetail,
            from: "page",
          },
        },
        "_blank",
      );
    },

    //申诉 确定成功回调
    closeOrderSuccess() {
      this.isShowCloseOrder = false;
      this.reset();
    },
    delaySuccess() {
      this.delayDiaShow = false;
      this.reset();
    },
    diaClose() {
      this.selRows = [];
      this.$refs.secTableRef.clearSelection();
    },
    reset() {
      this.selRows = [];
      this.$refs.secTableRef.clearSelection();
      this.initTableData();
    },
    // 页码变更
    handleCurrentChange(val) {
      this.page = val;
      this.initTableData();
    },
    // 条数变更
    handleSizeChange(val) {
      this.pageSize = val;
      this.initTableData();
    },
  },
};
</script>
<style lang="scss" scoped>
.receive-content {
  display: flex;
  margin: 15px 0 20px 0;
  i {
    font-size: 20px;
    color: #e6a23c;
    margin-right: 5px;
  }
}
.receive-opt-box {
  text-align: right;
}
.tip {
  padding-left: 100px;
  margin-bottom: 14px;
}
.table-container {
  .btn {
    position: absolute;
    z-index: 1;
    right: 20px;
  }
}
.deliver-data {
  max-height: 400px;
  overflow: auto;
  margin-bottom: 20px;
}
</style>

<style scoped>
::v-deep .el-icon-question:hover {
  color: #fa8919;
}
::v-deep .el-dialog__body {
  padding-top: 0 !important;
}
::v-deep .el-select {
  width: 100%;
}
.info {
  margin-left: 20px;
}
</style>
